<template>
  <div>
    <el-dialog
      title="订单核销"
      :visible.sync="open"
      width="1000px"
      :close-on-click-modal="false"
    >
      <el-table :data="postParams.sheetItem" border ref="multipleTable">
        <el-table-column v-if="prescriptionType == 1" type="selection" width="55" :selectable="selectable" />
        <el-table-column label="核销项目">
          <template slot-scope="{ row }">
            <span>{{ row.itemName }}</span>
            <div v-if="row.dailyPrescriptNum" class="colorY">每日{{row.dailyPrescriptNum}}贴，共{{row.days}}日，每次{{row.timeLength}}小时</div>
          </template>
        </el-table-column>
        <el-table-column label="总数" width="120px" align="center">
          <template slot-scope="{ row }">
            <span>{{ row.specsNum }}{{ row.unit }}</span>
          </template>
        </el-table-column>
        <el-table-column label="已核销" width="120px" align="center">
          <template slot-scope="{ row }">
            <span>{{ row.auditNum }}</span>
          </template>
        </el-table-column>
        <el-table-column label="待核销" width="120px" align="center">
          <template slot-scope="{ row }">
            <span class="fw-7">{{ row.maxNum }}{{ row.unit }}</span>
          </template>
        </el-table-column>

        <el-table-column label="核销数量">
          <template slot-scope="{ row }">
            <div v-if="!row.maxNum" class="shrink0 pr-10 color9">本项目已完成核销</div>
            <div v-else class="disFlxAC">
              <div class="shrink0 pr-10 color9">本次核销</div>
              <el-input-number
                v-model="row.unNum"
                :step="1"
                :min="0"
                :max="row.maxNum"
                size="mini"
                step-strictly
                controls-position="right"
                :disabled="prescriptionType != 1"
              >
              </el-input-number>
              <div class="pl-2">{{ row.unit }}</div>
            </div>
          </template>
        </el-table-column>
      </el-table>

      <div slot="footer" class="dialog-footer">
        <el-button :disabled="loading" @click="open = false">暂不核销</el-button>

        <el-input
          v-if="postParams.payWay !== 2 && prescriptionType != 1"
          v-model="postParams.checkCode"
          placeholder="请输入核销码"
          class="ml-20 codeInput"
        ></el-input>
        <el-button :class="{'codeBtn': prescriptionType != 1}" type="primary" :loading="loading" @click="submitForm"
          >确认核销</el-button
        >
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { checkOrderSettle } from "@/api/service"
export default {
  data() {
    return {
      open: false,
      prescriptionType: undefined,
      postParams: {}, // 核销对象
      loading: false,
    }
  },
  methods: {
    openModal(row) {
      this.postParams = {
        orderNo: row.orderNo,
        payWay: row.payWay,
        checkCode: "", // 核销码
        sheetItem: []
      };

      this.prescriptionType = row.parescriptOrder ? row.parescriptOrder.prescriptionType : undefined;

      if (this.prescriptionType == 1) { // 贴敷
        this.postParams.sheetItem = row.parescriptOrder.materialsDetail.map((v,index)=>{
          let label = v.materials.map(k=> k.materialsName).join(',') + ' / ' + v.acupoints.map(k=> k.acupointName).join(',');
          let remainNum = v.prescriptNum - (v.auditNum || 0); // 剩余可核销数量
          let defaultNum = 0;

          // 如果存在每日贴数，则默认核销数量为每日贴数
          if (v.dailyPrescriptNum) {
            defaultNum = Math.min(v.dailyPrescriptNum, remainNum);
          } else {
            defaultNum = remainNum > 0 ? 1 : 0; // 兼容老数据，保持原有逻辑
          }

          return {
            serialId: index + 1, // 序号
            itemName: `贴${index + 1}：（${label}）`,
            dailyPrescriptNum: v.dailyPrescriptNum, // 每日贴数
            days: v.days, // 共几日
            timeLength: v.timeLength, // 每次时长
            specsNum: v.prescriptNum, // 总数
            unNum: defaultNum, // 核销数量
            maxNum: remainNum, // 待核销数量
            auditNum: v.auditNum || 0, // 已核销数量
            unit: '贴',
          }
        })
      } else {
        row.sheetList.forEach((item) => {
          item.checkItem.forEach(v => {
            let _specsNum = item.serviceItems == 4 && item.prescriptNum ? item.prescriptNum * v.specsNum : v.specsNum;

            this.postParams.sheetItem.push({
              sheetId: item.sheetId,
              itemId: v.itemId,
              itemName: v.itemName,
              specsNum: _specsNum, // 总数
              unNum: _specsNum - (v.auditNum || 0), // 核销数量，默认最大
              maxNum: _specsNum - (v.auditNum || 0), // 待核销数量
              auditNum: v.auditNum || 0, // 已核销数量
              unit: v.unit ?? '项',
            });
          })
        });
      }
      this.open = true;

      this.$nextTick(() => {
        this.$refs.multipleTable.toggleAllSelection()
      })
    },
    closeModal() {
      Object.assign(this.$data, this.$options.data()); // 存在自定义校验规则不能重置data
    },

    // 设置表格中已核销完的项目禁用
    selectable(row,index){
      return row.maxNum ? true : false;
    },
    // 确认核销
    submitForm() {
      const that = this;
      if (that.postParams.payWay !== 2 && that.prescriptionType != 1 && !that.postParams.checkCode) {
        that.$message.error("请输入核销码");
        return;
      }

      that.loading = true;
      let params = {
        orderNo: that.postParams.orderNo,
        payWay: that.postParams.payWay,
        checkCode: that.postParams.checkCode,
        sheetItem: [],
        checkAuditRecord: [{ auditProject: "" }]
      };

      // 过滤掉核销数量为0的数据
      const _checkedRows = that.$refs.multipleTable.selection.filter(row => row.unNum > 0);

      if(that.prescriptionType == 1){ // 贴敷
        if(_checkedRows.length === 0){
          that.$message.error("请勾选需要核销并且核销数量大于0的项目");
          that.loading = false;
          return
        }
        _checkedRows.forEach((v, index) => {
          params.checkAuditRecord[index] = {
            serialId: v.serialId,
            auditProject: `${v.itemName || ''} +${v.unNum}${v.unit}。<br/>`,
            auditNum: v.unNum
          }
        })
      }else{
          that.postParams.sheetItem.forEach((v) => {
          params.sheetItem.push({
            sheetId: v.sheetId,
            itemId: v.itemId,
            auditNum: v.unNum,
          });
          params.checkAuditRecord[0].auditProject += `${v.itemName || ''}<span style="color: #F56C6C;padding-left: 5px;">(${v.unNum}${v.unit})</span><br/>`;
        });
      }
      checkOrderSettle(params).then((res) => {
        that.$message.success("核销成功");
        that.$emit("refresh");
        that.closeModal();
        that.loading = false;
      }).catch(()=>{
        this.loading = false;
      })
    },
  }
}
</script>

<style lang="scss" scoped>
.codeInput {
  width: 120px;
}
</style>
<style scoped>
.codeInput >>> .el-input__inner {
  border-top-right-radius: 0;
  border-bottom-right-radius: 0;
}
.codeBtn {
  border-top-left-radius: 0;
  border-bottom-left-radius: 0;
}
</style>
